﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.DynamicData;
using NotAClue.ComponentModel.DataAnnotations;

namespace NotAClue.Web.DynamicData
{
    public class AdvancedEntityTemplateFactory : System.Web.DynamicData.EntityTemplateFactory
    {
        public override string BuildEntityTemplateVirtualPath(string templateName, DataBoundControlMode mode)
        {
            string path = base.BuildEntityTemplateVirtualPath(templateName, mode);

            if (File.Exists(HttpContext.Current.Server.MapPath(path)))
                return path;

            return path.Replace("_" + mode.ToString(), "");
        }

        public override EntityTemplateUserControl CreateEntityTemplate(MetaTable table, DataBoundControlMode mode, string uiHint)
        {
            var et = table.GetAttribute<EntityUIHintAttribute>();
            if (et != null && !String.IsNullOrEmpty(et.UIHint))
                return base.CreateEntityTemplate(table, mode, et.UIHint);

            return base.CreateEntityTemplate(table, mode, uiHint);
        }

        public override string GetEntityTemplateVirtualPath(MetaTable table, DataBoundControlMode mode, string uiHint)
        {
            var et = table.GetAttribute<EntityUIHintAttribute>();
            if (et != null && !String.IsNullOrEmpty(et.UIHint))
                return base.GetEntityTemplateVirtualPath(table, mode, et.UIHint);

            return base.GetEntityTemplateVirtualPath(table, mode, uiHint);
        }
    }

    //public class AdvancedEntityTemplateUserControl :  System.Web.DynamicData.EntityTemplateUserControl
    //{
    //    protected override void AddedControl(System.Web.UI.Control control, int index)
    //    {
    //        var entityTemplate = control as EntityTemplate;
    //        if (entityTemplate != null)
    //        {
    //            var dynamicControl = entityTemplate.FindControlRecursive<DynamicControl>();
    //            if (dynamicControl != null)
    //            {
    //                dynamicControl.Mode = this.Mode;
    //                dynamicControl.ValidationGroup = this.ValidationGroup;
    //            }
    //        }

    //        base.AddedControl(control, index);
    //    }
    //}
}
